<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2018-06-26 09:17:22
 * @Description: token验证方法
 * @LastEditors: 李志刚
 * @LastEditTime: 2023-01-14 16:30:37
 * @FilePath: \www.gamemc.com\app\Http\Middleware\Jwt.php
 */

namespace App\Http\Middleware;

use Closure;
use App\Customize\Func;
use App\Customize\Sign;

class Jwt
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
			// 先验证签名
			$res = Sign::aes_decrypt($request->all());
			if ($res['code'] != 200) {
				return response()->json(['code' => 403, 'message' => $res['message'] . '...', 'result' => []]);
			}
			// 合并解析到的参数进请求中
			$request->merge($res['result']);
			// 验证 token，解析用户信息，判断权限
            $user = Func::verfiyToken($request->header('Authorization'),'g-token');
            $request->merge(['request_user_id'=>$user->id]);
            $response = $next($request);
            // 获取新token
            $response->header('authorization', Func::getToken($user->username,24));
            return $response;
		} catch (\Throwable $e) {
			return response()->json(['code' => 401, 'message' => '登录失效', 'result' => $e->getMessage()]);
		}
    }
}
